from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from protocol.ControlServerImpl import ControlServerImpl
from gen_py.protocol.control import SowarnaControlService
import threading, logging

class ControlServer(threading.Thread):
    def __init__(self, config, backend):
        threading.Thread.__init__(self)
        self._backend = backend
        self._config = config
        logging.info("Creating Control Server on port %s", self._config.control_port)
        self._handler = ControlServerImpl(self._backend)
        processor = SowarnaControlService.Processor(self._handler)
        transport = TSocket.TServerSocket(self._config.control_port)
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        self._server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)

    def run(self):
        logging.info("Starting the Control Server...")
        self._server.serve()
        logging.info("Control Server was stopped!")


class CacheServer(object):
    pass

class ServersFactory(object):
    def __init__(self, config, controlBackend, cacheBackend, dataBackend):
        self._config = config
        self._controlBackend = controlBackend
        self._cacheBackend = cacheBackend
        self._dataBackend = dataBackend
        
    def createControlServer(self):
        logging.debug("Creating Control Server")
        self._controlServer = ControlServer(self._config, self._controlBackend)
        return self._controlServer
    

class DataServer(object):
    pass